package com.hsy.bibc.modules.login;

import android.content.Intent;
import android.os.Bundle;
import android.os.IBinder;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.TextView;

import com.android.volley.VolleyError;
import com.deparse.dpframe.utils.DPGsonUtil;
import com.deparse.dpframe.utils.DPHttpUtil;
import com.hsy.bibc.common.Consts;
import com.hsy.bibc.R;
import com.hsy.bibc.modules.common.CommonBaseActivityWithSimpleActionBar;
import com.hsy.bibc.modules.main.MainActivity;
import com.hsy.bibc.utils.CommonUtils;
import com.hsy.bibc.utils.HttpUtil;
import com.tencent.android.tpush.XGPushManager;

import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by hsy on 2016/3/23.
 */
public class LoginActivity extends CommonBaseActivityWithSimpleActionBar implements View.OnClickListener {
    private EditText mUserNameEditText;
    private EditText mUserPassEditText;
    private TextView mForgetTextView, finish;
    private DPHttpUtil.HttpCallback callback = new DPHttpUtil.HttpCallback() {
        @Override
        public void onSuccess(int what, String response) {
            if (0 == what) {
                LoginGsonData.Result result = DPGsonUtil.fromJson(response, LoginGsonData.Result.class);

                saveUserInformation(result);

                CommonUtils.hideProgressDialog();

                XGPushManager.registerPush(LoginActivity.this, result.getUser().getPhone());

                Intent intent = new Intent(LoginActivity.this, MainActivity.class);

                startActivity(intent);

//                HttpUtil.httpGet(getApplicationContext(), 1, Consts.API_GET_CONTACTS + "?version=" + CommonUtils.getContactsVersion(getApplicationContext()), callback);

            }
        }

        @Override
        public void onError(int what, int type, VolleyError error) {
            if (0 == what) {
                CommonUtils.hideProgressDialog();
            }

        }

        @Override
        public void onMsgError(int what, int type, String msg) {
            CommonUtils.hideProgressDialog();
        }
    };

    private void saveUserInformation(LoginGsonData.Result result) {

        CommonUtils.saveToken(LoginActivity.this, result.getToken());

        CommonUtils.saveUserAddress(LoginActivity.this, result.getUser().getAddress());
        CommonUtils.saveUserDH(LoginActivity.this, result.getUser().getIs_dh());
        CommonUtils.saveUserFP(LoginActivity.this, result.getUser().getIs_fp());
        CommonUtils.saveUserId(LoginActivity.this, result.getUser().getId());
        CommonUtils.saveUserLogo(LoginActivity.this, result.getUser().getLogo());
        CommonUtils.saveUserName(LoginActivity.this, result.getUser().getName());
        CommonUtils.saveUserPhone(LoginActivity.this, result.getUser().getPhone());
        CommonUtils.saveUserXf(LoginActivity.this, result.getUser().getIs_xf());
        CommonUtils.saveUserTel(LoginActivity.this, result.getUser().getTel());
        CommonUtils.saveUserMap(LoginActivity.this, result.getUser().getMap());
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
        View view = this.getCurrentFocus();
        if (view != null) {
            IBinder a = view.getWindowToken();
            if (a != null) {
                return imm.hideSoftInputFromWindow(this.getCurrentFocus().getWindowToken(), 0);
            }
        }


        return super.onTouchEvent(event);
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        setLeftButtonVisiblity(View.GONE);
        setTitle(R.string.login);
        setTitleTextColor(R.color.tab_text_color_normal);

        mForgetTextView = F(R.id.find_password);
        mForgetTextView.setOnClickListener(this);


        finish = F(R.id.finish);
        finish.setOnClickListener(this);

        mUserNameEditText = F(R.id.phone);
        mUserPassEditText = F(R.id.password);

    }

    private void postHttp() {
        CommonUtils.showProgressDialog(this);
        Map<String, String> data = new HashMap<>();
        data.put("user_name", mUserNameEditText.getText().toString());
        data.put("user_password", mUserPassEditText.getText().toString());
        data.put("app_type", "2");
        HttpUtil.httpPostWithParams(LoginActivity.this, 0, Consts.Apis.POST_AUTH_LOGIN, data, callback);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.finish:
                if (check()) {
                    postHttp();
                }
                break;
            case R.id.find_password:
                startActivity(ForgetPasswordActivity.class);
                break;
            default:
                break;
        }
    }

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            moveTaskToBack(true);
            return true;
        }
        return super.onKeyUp(keyCode, event);
    }

    private boolean check() {
        if (isEmpty(mUserNameEditText.getText().toString().trim())) {
            showToast(R.string.forget_phone);
            return false;
        }
        if (isEmpty(mUserPassEditText.getText().toString().trim())) {
            showToast(R.string.forget_password);
            return false;
        }
        Pattern p = Pattern.compile("^[0-9]{11}$");
        Matcher m = p.matcher(mUserNameEditText.getText().toString().trim());
        if (!m.matches()) {
            showToast(R.string.txt_user_name_format_error);
            return false;
        }
        Pattern p1 = Pattern.compile("^.{6,18}$");
        Matcher m1 = p1.matcher(mUserPassEditText.getText().toString().trim());
        if (!m1.matches()) {
            showToast(R.string.txt_user_pass_length_error);
            return false;
        }
        return true;
    }
}